package com.study02.zigzagarrangement;

public class ZTest2 {
    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        String convert = convert(s, 4);
        System.out.println(convert);

    }

    /**
     * @param s
     * @param nums
     * @return
     */
    public static String convert(String s, int nums) {
        //判断字符串长度
        int n = s.length();
        //判断如果nums多长度是1 或者nums的值大于字符串的长度就直接返回；
        if (nums == 1 || nums >= n) return s;

        /**
         *          P A Y P A L I S H I R I N G
         *         nums = 3              nums = 5
         *         P   A   H   N         P             H
         *         A P L S I I G         A          S  I
         *         Y   I   R             Y      I      R
         *         nums = 4;             P   L         I    G
         *         P     I    N          A             N
         *         A   L S  I G
         *         Y A   H R
         *         P     I
         *         int c = (n + t - 1) / t * (r - 1);
         */

        //它一个周期的字母是nums的二倍减2
        int t = nums * 2 - 2;
        //周期列数
        int cycRow = nums - 1;
        //总列说
        int c = n / t * cycRow;
        if (n % t > nums) {
            c += 2;
        } else if (n % t <= nums) {
            c += 1;
        }
        char[][] ch = new char[nums][c];
        int x = 0, y = 0;
        for (int i = 0; i < n; i++) {
            ch[x][y] = s.charAt(i);
            //如果x的余数小于列数就加1 如果大于或等于就减一
            if (i % t < cycRow) {
                //x向下移动
                ++x;
            } else {
                //x向右上方移动
                --x;
                //行向右移
                ++y;
            }
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (char[] row : ch) {
           for (char siCh:row){
               if (siCh != 0){
                   stringBuilder.append(siCh);
               }
           }
        }
        return stringBuilder.toString();
    }
}
